from fastapi import FastAPI, Request, HTTPException
import hmac
import hashlib
import subprocess
import os

app = FastAPI()

# 配置
SECRET = "123456789"  # 与Gitee上设置一致
DEPLOY_SCRIPT_PATH = "/home/aps/ai/mobile-ai-app/T.sh"  # 部署脚本路径

@app.get("/")
async def get_request():
    data = "hello-world!"
    return {
        "code": 200,
        "msg": "请求成功",
        "data": {"data": data}
    }

def verify_signature(payload: bytes, signature: str) -> bool:
    """验证Gitee签名"""
    if not signature.startswith("sha256="):
        return False
    signature_hash = signature[7:]
    local_hash = hmac.new(SECRET.encode(), payload, hashlib.sha256).hexdigest()
    return hmac.compare_digest(local_hash, signature_hash)


def run_deploy_script():
    """执行部署脚本"""
    if not os.path.exists(DEPLOY_SCRIPT_PATH):
        return "部署脚本不存在", False

    try:
        result = subprocess.run(
            ["bash", DEPLOY_SCRIPT_PATH],
            capture_output=True,
            text=True,
            timeout=30
        )
        return f"部署成功: {result.stdout}", True
    except Exception as e:
        return f"部署失败: {str(e)}", False


@app.post("/webhook")
async def handle_webhook(request: Request):
    # 获取签名和事件类型
    signature = request.headers.get("X-Gitee-Signature")
    event_type = request.headers.get("X-Gitee-Event")

    if not signature:
        raise HTTPException(status_code=400, detail="缺少签名")

    # 验证签名
    payload = await request.body()
    if not verify_signature(payload, signature):
        raise HTTPException(status_code=403, detail="签名无效")

    # 只处理push事件
    if event_type == "push":
        message, success = run_deploy_script()
        return {"status": "success" if success else "failed", "message": message}

    return {"status": "ignored", "message": f"不处理{event_type}事件"}


if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8000)
